﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace template_dll
{
    public partial class Form9 : Form
    {
        public Form9()
        {
            InitializeComponent();
        }

        public SqlConnection conn;
        public int actionId = 0;
        public DataTable drugs;
        private DrugsFilter.DrugsFilter f2;
        public int typeAction = 0;

        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Add();
        }
        
        private void button2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                {
                    dataGridView1.Rows.RemoveAt(row.Index);
                }
            }
            else
                MessageBox.Show("Не выбрана ни одна строка");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                SqlStorProc.sp_params[] p1 = new SqlStorProc.sp_params[1];
                p1[0].name = "@actionId";
                p1[0].value = actionId;
                new SqlStorProc().SqlProcExecNonQuery(conn, "pas_Actions_ParentDrugsDel", 30, p1);
                if(dataGridView1.RowCount > 0)
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[4];
                        par[0].name = "@actionid";
                        par[0].value = actionId;
                        par[1].name = "@drcode";
                        par[1].value = Convert.ToInt32(row.Cells["Column1"].Value);
                        par[2].name = "@drcode_p";
                        par[2].value = Convert.ToInt32(row.Cells["Column3"].Value);
                        par[3].name = "@perc";
                        par[3].value = Convert.ToDouble(row.Cells["Column5"].Value);
                        new SqlStorProc().SqlProcExecNonQuery(conn, "pas_Actions_ParentDrugsIns", 30, par);
                    }
                MessageBox.Show("Данные сохранены");
                this.DialogResult = DialogResult.OK;
            }
            catch(Exception)
            {
                MessageBox.Show("При сохранении возникли ошибки.\nПроверьте данные");
            }
        }

        private void Form9_Load(object sender, EventArgs e)
        {
            try
            {
                if (actionId > 0)
                {
                    SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[1];
                    par[0].name = "@actionid";
                    par[0].value = actionId;
                    DataTable dt = new SqlStorProc().SqlProcExecWithQueryOneTable(conn, "pas_Actions_ParentDrugsSel", 300, par);
                    foreach (DataColumn c in dt.Columns)
                        c.DefaultValue = null;

                    if (drugs != null && typeAction == 1)
                    {
                        foreach (DataRow row in drugs.Rows)
                        {
                            bool fl = false;
                            foreach (DataRow rdt in dt.Rows)
                            {
                                if (row["Код"].ToString() == rdt["Акция - Код товара"].ToString())
                                {
                                    fl = true;
                                }
                            }
                            if (!fl)
                            {
                                object[] ob = new object[5] { row["Код"], row["Товар"], null, null, null };
                                dt.Rows.Add(ob);
                            }
                        }
                    }
                    foreach (DataRow row in dt.Rows)
                    {
                        object[] obj = new object[5] { row[0], row[1], row[2], row[3], row[4] };
                        dataGridView1.Rows.Add(obj);
                    }
                    if (typeAction == 3)
                    {
                        dataGridView1.Columns[0].Visible = false;
                        dataGridView1.Columns[1].Visible = false;
                    }
                }
                else
                {
                    MessageBox.Show("Не выбрана акция");
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.Close();
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 || e.ColumnIndex == 1)
            {
                if (DrugFilter(false))
                {
                    dataGridView1[0, e.RowIndex].Value = f2.dt_drug_tmp.Rows[0]["Код"];
                    dataGridView1[1, e.RowIndex].Value = f2.dt_drug_tmp.Rows[0]["Товар"];
                    dataGridView1.Refresh();
                }
            }
            if (e.ColumnIndex == 2 || e.ColumnIndex == 3)
            {
                if (DrugFilter(true))
                {
                    int fl = 0;
                    object perc = null;
                    if (f2.dt_drug_tmp.Rows.Count > 1)
                    {
                        Form11 f11 = new Form11();
                        if (f11.ShowDialog() == DialogResult.Yes)
                            perc = f11.percent;
                        f11.Close();
                        f11 = null;
                    }
                    foreach (DataRow row in f2.dt_drug_tmp.Rows)
                    {
                        if (fl == 0)
                        {
                            dataGridView1[2, e.RowIndex].Value = row["Код"];
                            dataGridView1[3, e.RowIndex].Value = row["Товар"];
                            if (perc != null) dataGridView1[4, e.RowIndex].Value = perc;
                            fl++;
                        }
                        else
                        {
                            object[] ob = new object[5] { dataGridView1[0, e.RowIndex].Value, dataGridView1[1, e.RowIndex].Value, row["Код"], row["Товар"], perc };
                            dataGridView1.Rows.Add(ob);
                            fl++;
                        }
                    }
                    dataGridView1.Refresh();
                }
            }
        }

        private bool DrugFilter(bool parent)
        {
            bool res = false;
            try
            {
                while (true)
                {
                    string namechcol = "Флаг";
                    if (f2 == null)
                    {
                        f2 = new DrugsFilter.DrugsFilter();

                        SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[2];
                        par[0].name = "@arch";
                        par[0].value = "нет";
                        par[1].name = "@top";
                        par[1].value = "3000";

                        f2.dt_drug = new SqlStorProc().SqlProcExecWithQueryOneTable(conn, "pas_AllDrugsSel", 300, par).Copy();
                        foreach (DataColumn dc in f2.dt_drug.Columns)
                        {
                            if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                            else dc.ReadOnly = false;
                        }
                        f2.rb = true;
                        f2.dt_drug_tmp = f2.dt_drug.Clone();
                        f2.sqlconn = conn;
                        f2.namechcol = namechcol;
                        f2.dataGridView1.DataSource = f2.dt_drug_tmp.DefaultView;
                    }
                  
                    f2.ShowDialog();

                    if (f2.dt_drug_tmp.Rows.Count == 0)
                    {
                        MessageBox.Show("Не был выбран товар");
                        break;
                    }
                    if (f2.dt_drug_tmp.Rows.Count > 1 && !parent) MessageBox.Show("Выбрано более одного товара!");
                    //if (f2.dt_drug_tmp.Rows.Count == 1)
                    //{
                    //    res[0] = f2.dt_drug_tmp.Rows[0]["Код"];
                    //    res[1] = f2.dt_drug_tmp.Rows[0]["Товар"];
                    //    break;
                    //}
                    if ((f2.dt_drug_tmp.Rows.Count > 0 && parent) || (f2.dt_drug_tmp.Rows.Count == 1 && !parent))
                    {
                        res = true;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return res;
        }

        private void Form9_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (f2 != null)
                {
                    f2.Close();
                    f2 = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
